package source.model;

import java.util.Vector;

import source.events.action.Action;
import source.events.action.MoveDirection;
import source.model.type.*;

import source.view.*;

public class Laser extends Item implements Useable{

	private int distance;
	private int damage;
	
	public Laser(){
		this(5, 10);
	}
	
	public Laser(int distance, int damage){
		super(ItemType.LASER);
		this.distance=distance;
		this.damage=damage;
	}
	
	public int distance(){
		return distance;
	}
	
	public int damage(){
		return damage;
	}
	
	public Action use(){
		return new Action() {
			public ActionResult execute( DataHandler dh ) {
				GameObject go = dh.getCurrentSelection();
				if ( go.objectType() != GameObjectType.UNIT ) return ActionResult.IMPOSSIBLE;
				
				Unit unit = (Unit)go;
				
				MoveDirection facing=unit.getFacing();
				Position[] affectedPositions=new Position[distance];
				Position executorPosition=dh.positionQuery(unit.objectID());
				affectedPositions[0]=new Position(executorPosition.getX()+facing.xChange(), executorPosition.getY()+facing.yChange());
				for(int i=1; i<distance; i++){
					affectedPositions[i]=new Position(affectedPositions[i-1].getX()+facing.xChange(), affectedPositions[i-1].getY()+facing.yChange());
				}
				Vector<Unit> affectedUnits=new Vector<Unit>();
				for(int i=0; i<affectedPositions.length; i++){
					if(affectedPositions[i].isValid());
					GameObject[] go1=dh.positionQuery(affectedPositions[i], GameObjectType.TERRAIN);
					GameObject[] go2=dh.positionQuery(affectedPositions[i], GameObjectType.ITEM);
					Vector<Item> item=new Vector<Item>();
					for(int k=0; k<go2.length; k++)
						item.add((Item)go2[k]);
					Terrain terrain=(Terrain)go1[0];
					if(terrain.getType().equals(TerrainType.PLANET))
						break;
					if(go2.length!=0&&(item.get(i).getItemType().equals(ItemType.COMET)||item.get(i).getItemType().equals(ItemType.DERELICTOREREFINERY)))
						break;
					GameObject[] gameObject=dh.positionQuery(affectedPositions[i], GameObjectType.UNIT);
					for(int j=0; j<gameObject.length; j++){
						affectedUnits.add((Unit)gameObject[j]);
					}
				}
				if(affectedUnits.isEmpty()){
					MainScreen.writeToConsole("No units were hit by the laser");
					return ActionResult.FAILED;
				}
				for(Unit u : affectedUnits){
					u.modHealth(-damage);
				}
				MainScreen.writeToConsole("Laser has been fired");
				return ActionResult.SUCCESS;
			}
		};
	}
}
